package com.android.quizvoctrainer;

import java.io.File;
import java.io.IOException;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
	private static final int REQUEST_SCAN = 0;
	private static Logger logger = Logger.getLogger("com.android.quizvoctrainer");
	private static FileHandler loggerfh;
	private final CharSequence nl = "\n";
	private CharSequence path = "";
	private CharSequence listsPath = "";
	private CharSequence[] listFilenames = new CharSequence[]{};
	private CharSequence[] listTitles = new CharSequence[]{};
	final CharSequence[] nbrQuestions = {"5", "10", "20", "50", "100"};
    /** Called when the activity is first created. */
	private AlertDialog.Builder aChooseDialog;
	private AlertDialog.Builder aAlertDialog;
	private TextView tvList;
	private Button bChooseList;
	private TextView tvNumberQuestions;
	private Button bChooseNumberQuestions;
	private Button bRunTest;
	private Button bEnterCodeImportList;
	private Button bScanCodeImportList;
    private EditText etCode;
	private QuizVocList currentList = null;
	private int currentNumberOfQuestions = 20;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        initApplication();
    };
    public void alertdebug(String text) {
    	Toast.makeText(getBaseContext(), text,Toast.LENGTH_LONG).show();
    }
    public static void debug(String text) {
    	logger.log(Level.FINEST, text);
    }
    public static void info(String text) {
    	logger.log(Level.INFO, text);
    }
    public static void warn(String text) {
    	logger.log(Level.WARNING, text);
    }
    public static void crit(String text) {
    	logger.log(Level.SEVERE, text);
    }
	private void initApplication() {
        try {
        	loggerfh = new FileHandler(getExternalFilesDir(null).getAbsolutePath() + "/logs/quizvoctrainer.log");
        	loggerfh.setFormatter(new SimpleFormatter());
			logger.addHandler(loggerfh);
			logger.setLevel(Level.ALL);
		} catch (IOException e) {
			debug(e.getMessage());
		}
        tvList = (TextView)findViewById(R.id.textlist);
        bChooseList = (Button)findViewById(R.id.buttonlist);
        bChooseList.setOnClickListener(bChooseListOnClick);
        tvNumberQuestions = (TextView)findViewById(R.id.textnumberquestions);
        bChooseNumberQuestions = (Button)findViewById(R.id.buttonnumberquestions);
        bChooseNumberQuestions.setOnClickListener(bChooseListOnClick);
        bRunTest = (Button)findViewById(R.id.buttonrun);
        bRunTest.setOnClickListener(bRunTestOnClick);
        aChooseDialog = new AlertDialog.Builder(this);
        aAlertDialog = new AlertDialog.Builder(this);
        path = getExternalFilesDir(null).getPath();
        listsPath = path + "/lists";
        bEnterCodeImportList = (Button)findViewById(R.id.buttonentercodeimport);
        bEnterCodeImportList.setOnClickListener(bEnterCodeImportListOnClick);
        bEnterCodeImportList.setText(R.string.enter_code_import_list);
        bScanCodeImportList = (Button)findViewById(R.id.buttonscancodeimport);
        bScanCodeImportList.setOnClickListener(bScanCodeImportListOnClick);
        bScanCodeImportList.setText(R.string.scan_code_import_list);
        //////////////////////////////////////////////
        readAvailableLists();
        selectNewList(-1);
        selectNewNumberOfQuestions(2);
	};
	public void showDialogList(int title, CharSequence[] items, DialogInterface.OnClickListener listener) {
		aChooseDialog.setTitle(title);
		aChooseDialog.setItems(items, listener);
		AlertDialog myalert = aChooseDialog.create();
		myalert.show();
	}
	public void showAlertDialog(int title, int text, int button) {
		aAlertDialog.setTitle(title);
		aAlertDialog.setMessage(text);
		aAlertDialog.setNeutralButton(button, null);
		AlertDialog myalert = aAlertDialog.create();
		myalert.show();
	}
    private OnClickListener bEnterCodeImportListOnClick = new OnClickListener() {
		public void onClick(View v) {
			if (!isNetworkAvailable()) {
				showAlertDialog(R.string.oops, R.string.no_internet_access, R.string.button_ok);
			} else {
				enterCodeImportListOpenDialog();
			}
		}
	};
	private void enterCodeImportListOpenDialog() {
        LayoutInflater factory = LayoutInflater.from(this);            
        final View textEntryView = factory.inflate(R.layout.importdialog, null);
        AlertDialog.Builder alert = new AlertDialog.Builder(this);
        alert.setTitle(R.string.import_list);
        alert.setMessage(R.string.type_or_scan);
        alert.setView(textEntryView);
        etCode = (EditText)textEntryView.findViewById(R.id.editcode);
        alert.setPositiveButton(R.string.button_import, bLaunchImportOnClick);
        alert.setNegativeButton(R.string.button_cancel, null);
        alert.show();
	}
	private OnClickListener bScanCodeImportListOnClick = new OnClickListener() {
		public void onClick(View v) {
			Intent intent = new Intent("com.google.zxing.client.android.SCAN");
	        intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
	        try {
	        	startActivityForResult(intent, REQUEST_SCAN);
	        } catch (ActivityNotFoundException e) {
	        	alertdebug(getApplicationContext().getString(R.string.scanner_not_installed));
	        }			
		}
	};
	private DialogInterface.OnClickListener bLaunchImportOnClick = new DialogInterface.OnClickListener() {
		public void onClick(DialogInterface dialog, int which) {
			importListFromGoogleShortUrlCode(etCode.getText().toString());
		}
	};
	private void importListFromGoogleShortUrlCode(String code) {
		String result = Utils.getTxtFromGoogleDocWithGooglShortUrl(code);
		QuizVocList newList = new QuizVocList();
		newList.fromString(result);
		newList.setFilename(newList.getName() + ".qvt");
		Utils.saveListToFile(newList, listsPath, newList.getFilename());
		readAvailableLists();
	}
    private OnClickListener bChooseListOnClick = new OnClickListener() {
		public void onClick(View v) {
			if (v.getId() == R.id.buttonlist) showDialogList(R.string.choose_list, listTitles, aChooseListOnClick);
			if (v.getId() == R.id.buttonnumberquestions) showDialogList(R.string.choose_number_questions, nbrQuestions, aChooseNumberQuestionsOnClick);
		}
	};
	public void onActivityResult(int reqCode, int resCode, Intent intent) {
	    if (REQUEST_SCAN == reqCode) {
	        if (RESULT_OK == resCode) {
	            String contents = intent.getStringExtra("SCAN_RESULT");
				String result = Utils.getTxtFromGoogleDocWithId(contents);
				debug(result);
	        } else if (RESULT_CANCELED == resCode) {
	            debug("Scan annulé");
	        }
	    }
	}
	private OnClickListener bRunTestOnClick = new OnClickListener() {
		public void onClick(View v) {
			startRunTestActivity();
		}
	};
	///////////////////////////////////////////////////////////////////////////////////////////////////
	private DialogInterface.OnClickListener aChooseListOnClick = new DialogInterface.OnClickListener() {
		public void onClick(DialogInterface dialog, int which) {
			selectNewList(which);
		}
	};
	
	private DialogInterface.OnClickListener aChooseNumberQuestionsOnClick = new DialogInterface.OnClickListener() {
		public void onClick(DialogInterface dialog, int which) {
			selectNewNumberOfQuestions(which);
		}
	};
	////////////////////////////////////////////////////////////////////////////////////////////////////
	private void selectNewList (int newListIndex) {
		if (newListIndex == -1) {
			currentList = new QuizVocList();
			tvList.setText(R.string.no_current_list);
		} else {
			currentList = Utils.loadCurrentListFromFile(listsPath, listFilenames[newListIndex]);
			String newLabel = currentList.getName() + " (" + currentList.getLength() + ")";
			tvList.setText(newLabel);
		}
		bRunTest.setEnabled(currentList.getLength() > 0);
	}
	private void selectNewNumberOfQuestions (int newNumberOfQuestionIndex) {
		currentNumberOfQuestions = new Integer((String)nbrQuestions[newNumberOfQuestionIndex]).intValue();
		String newLabel = getApplicationContext().getString(R.string.number_of_questions)
			+ " : " + currentNumberOfQuestions;
		tvNumberQuestions.setText(newLabel);
	}
	private void readAvailableLists() {
		File mydir = new File(getExternalFilesDir(null) + "/lists");
		File[] files = mydir.listFiles();
		listTitles = new CharSequence[files.length];
		listFilenames = new CharSequence[files.length];
		for (int i=0;i < files.length;i++) {
			listFilenames[i] = files[i].getName();
			listTitles[i] = files[i].getName();
		}
	}
	private boolean isNetworkAvailable() {
	    ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
	    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
	    return activeNetworkInfo != null;
	}
	private void startRunTestActivity() {
		Intent intent = new Intent(this, RunTestActivity.class);
		intent.putExtra(Utils.currentListFilenameKey, currentList.getFilename());
		intent.putExtra(Utils.numberOfQuestionsKey, currentNumberOfQuestions);
		startActivity(intent);
	}
	

}
